package com.xiaomage.textviewaddimage

import android.content.Context
import android.graphics.*
import android.support.annotation.IntDef
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.TextView

/**
 * Created by Administrator on 2018/3/26 0026.
 *
 * //测量文字长度:paint.measureText(text)
 */
class TextViewAddImage: View {
    private var rightImageId=0
    private var text=""
    private var textSize=12f
    private val paint=Paint()
    private var textColor=Color.parseColor("#ffffff")
    //行高
    private var rowHeight=0f
    //图片距离文字的宽度:dp
    private var drawablePadding=5f
    private var bitmap:Bitmap?=null
    private var bitmapWidth=1f
    private var bitmapHeight=1f
    //一行可以装下的字的个数
    private var oneLineCount=1
    //单行基线坐标
    private var baseLineY=0f
    private val baseLineX = 0f

    constructor(context: Context):super(context)
    constructor(context: Context,attributeSet: AttributeSet):super(context,attributeSet){
        val typedArray=context.obtainStyledAttributes(attributeSet,R.styleable.TextViewAddImage)
        rightImageId=typedArray.getResourceId(R.styleable.TextViewAddImage_rightImage,0)
        text=typedArray.getString(R.styleable.TextViewAddImage_text)
        textSize=typedArray.getDimension(R.styleable.TextViewAddImage_textSize,12f)
        textColor=typedArray.getColor(R.styleable.TextViewAddImage_textColor,Color.parseColor("#ffffff"))
        rowHeight=typedArray.getDimension(R.styleable.TextViewAddImage_rowHeight,0f)
        drawablePadding=typedArray.getDimension(R.styleable.TextViewAddImage_drawablePadding,5f)
        paint.textSize=sp2px(textSize)//以px为单位
        paint.color=textColor
        bitmap=BitmapFactory.decodeResource(resources,rightImageId)
        bitmapHeight=sp2px(textSize)
        bitmapWidth= (bitmapHeight*(bitmap?.width?:1))/(bitmap?.height?:1)
        //根据矩阵缩放图片
        val myMatrix=Matrix()
        myMatrix.postScale(bitmapWidth/(bitmap?.width?:1),bitmapWidth/(bitmap?.height?:1))
        bitmap= Bitmap.createBitmap(bitmap,0,0,(bitmap?.width?:1),
                (bitmap?.height?:1),myMatrix,true)
        //求出基线
        val fm=paint.fontMetrics
        baseLineY=0-fm.top

    }
    constructor(context: Context,attributeSet: AttributeSet,intDef: Int):super(context,attributeSet,intDef)
    init {

    }



    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val measureWidth = View.MeasureSpec.getSize(widthMeasureSpec)
        var textWidth=paint.measureText(text)
        var n=0
        //1.循环绘制文本：一行绘制的数量
        oneLineCount= (measuredWidth/paint.measureText("赵")).toInt()
        while(true){
            var needWidth=textWidth+bitmapWidth+dip2px(drawablePadding)
            if(needWidth<=measuredWidth){
                //此时可以一行显示
                break
            }else{
                n++
                textWidth-=oneLineCount*paint.measureText("赵")
            }
        }
        setMeasuredDimension(measureWidth, ((n+1)*sp2px(rowHeight)).toInt())
    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var textWidth=paint.measureText(text)
        var n=0
        //1.循环绘制文本：一行绘制的数量
        oneLineCount= (measuredWidth/paint.measureText("赵")).toInt()
        while(true){
            var needWidth=textWidth+bitmapWidth+dip2px(drawablePadding)
            if(needWidth<=measuredWidth){
                //此时可以一行显示
                break
            }else{
                n++
                textWidth-=oneLineCount*paint.measureText("赵")
            }
        }
        //开始布局
        Log.e("测试，图片id：","一行文本绘制的数量:"+oneLineCount)
        Log.e("测试，图片id：","需要多少行:"+n)
        if(text.length%oneLineCount==0 && text.length>1){
            //如果一行正好排满，此时最后一个文字换行
            text=text.substring(0,text.length-1)+" "+text.subSequence(text.length-1,text.length)
        }
        if(n>0){
            for(i in 0 until n+1){
                var str=""
                if(i==0){
                    str=text.substring(0,oneLineCount)
                    //写文字
                    canvas.drawText(str, baseLineX, baseLineY, paint)
                }else if(i==n){
                    str=text.substring(oneLineCount*i,text.length)
                    //写文字
                    canvas.drawText(str, baseLineX, baseLineY+i*sp2px(rowHeight), paint)
                    //绘制bitmap

                    canvas.drawBitmap(bitmap,paint.measureText(str)+dip2px(drawablePadding),
                            i*sp2px(rowHeight)+sp2px(rowHeight-textSize)/2,paint)
                }else{
                    str=text.substring(oneLineCount*i,oneLineCount*(i+1))
                    //写文字
                    canvas.drawText(str, baseLineX, baseLineY+i*sp2px(rowHeight), paint)
                }
            }
        }else{
            canvas.drawText(text.toString(), baseLineX, baseLineY, paint)
            //绘制bitmap
            canvas.drawBitmap(bitmap,paint.measureText(text)+dip2px(drawablePadding),
                    sp2px(rowHeight-textSize)/2,paint)
        }
    }

    fun sp2px( spValue: Float): Float{
        val fontScale = context.resources.displayMetrics.scaledDensity
        return spValue * fontScale + 0.5f
    }

    fun dip2px(dpValue: Float): Int {
        val scale =context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}